/**
 * AnimationManager - 动画管理器
 * 管理动画状态、关键帧插值、动画过渡
 */

// 动画配置
const ANIMATIONS = {
  idle: {
    duration: 4000,
    loop: true,
    keyframes: {
      body: {
        y: [0, -6, 0],
        rotation: [0, 1, 0],
        scale: [1, 1, 1]
      },
      tail: {
        rotation: [25, 45, 25]
      },
      ears: {
        left: { rotation: [-15, -12, -15] },
        right: { rotation: [15, 12, 15] }
      }
    }
  },
  
  happy: {
    duration: 800,
    loop: false,
    keyframes: {
      body: {
        scale: [1, 1.15, 1],
        y: [0, -8, 0]
      },
      eyes: {
        scale: [1, 1.2, 1]
      },
      mouth: {
        curve: [0.5, 0.9, 0.5]
      },
      tail: {
        rotation: [25, 60, 25]
      }
    }
  },
  
  excited: {
    duration: 1000,
    loop: true,
    keyframes: {
      body: {
        rotation: [0, -3, 3, -3, 0],
        scale: [1, 1.05, 1.05, 1.05, 1],
        y: [0, -4, -4, -4, 0]
      },
      tail: {
        rotation: [25, 60, 25, 60, 25]
      },
      limbs: {
        offset: [0, 2, 0, -2, 0]
      },
      ears: {
        left: { rotation: [-15, -20, -10, -20, -15] },
        right: { rotation: [15, 20, 10, 20, 15] }
      }
    }
  },
  
  sad: {
    duration: 3000,
    loop: true,
    keyframes: {
      body: {
        y: [0, 3, 0],
        scale: [1, 0.98, 1]
      },
      ears: {
        left: { rotation: [-15, -25, -15] },
        right: { rotation: [15, 25, 15] }
      },
      eyes: {
        scale: [1, 0.8, 1]
      },
      mouth: {
        curve: [0.5, 0.2, 0.5]
      },
      tail: {
        rotation: [25, 15, 25]
      }
    }
  },
  
  dragging: {
    duration: 0,
    loop: false,
    keyframes: {
      body: {
        scale: [1.1],
        rotation: [0]
      },
      tail: {
        rotation: [45]
      }
    }
  }
}

class AnimationManager {
  constructor() {
    this.currentAnimation = 'idle'
    this.animationStartTime = 0
    this.transitionProgress = 1 // 1表示过渡完成
    this.transitionDuration = 300 // 过渡时长（毫秒）
    this.previousFrame = null
    this.animations = ANIMATIONS
  }

  /**
   * 切换动画
   */
  switchAnimation(animationType, timestamp) {
    if (animationType === this.currentAnimation) return
    
    // 保存当前帧作为过渡起点
    this.previousFrame = this.getCurrentFrame(timestamp)
    
    // 切换动画
    this.currentAnimation = animationType
    this.animationStartTime = timestamp
    this.transitionProgress = 0
  }

  /**
   * 获取当前动画帧
   */
  getCurrentFrame(timestamp) {
    const animation = this.animations[this.currentAnimation]
    if (!animation) {
      console.warn('Animation not found:', this.currentAnimation)
      return this.getDefaultFrame()
    }
    
    // 计算动画进度
    let progress = 0
    if (animation.duration > 0) {
      const elapsed = timestamp - this.animationStartTime
      progress = (elapsed % animation.duration) / animation.duration
      
      // 如果不循环且已完成，保持在最后一帧
      if (!animation.loop && elapsed >= animation.duration) {
        progress = 1
      }
    }
    
    // 计算当前帧
    const frame = this.interpolateKeyframes(animation.keyframes, progress)
    
    // 如果在过渡中，混合前后帧
    if (this.transitionProgress < 1 && this.previousFrame) {
      const transitionElapsed = timestamp - this.animationStartTime
      this.transitionProgress = Math.min(1, transitionElapsed / this.transitionDuration)
      
      return this.blendFrames(this.previousFrame, frame, this.transitionProgress)
    }
    
    return frame
  }

  /**
   * 插值关键帧
   */
  interpolateKeyframes(keyframes, progress) {
    const frame = {}
    
    for (const [part, values] of Object.entries(keyframes)) {
      if (typeof values === 'object' && !Array.isArray(values)) {
        // 嵌套对象（如ears.left）
        frame[part] = {}
        for (const [subPart, subValues] of Object.entries(values)) {
          frame[part][subPart] = this.interpolateValues(subValues, progress)
        }
      } else {
        // 直接值
        frame[part] = this.interpolateValues(values, progress)
      }
    }
    
    return frame
  }

  /**
   * 插值单个属性的值
   */
  interpolateValues(values, progress) {
    const result = {}
    
    for (const [key, keyframeArray] of Object.entries(values)) {
      if (Array.isArray(keyframeArray)) {
        result[key] = this.interpolateArray(keyframeArray, progress)
      } else {
        result[key] = keyframeArray
      }
    }
    
    return result
  }

  /**
   * 在关键帧数组中插值
   */
  interpolateArray(keyframes, progress) {
    if (keyframes.length === 0) return 0
    if (keyframes.length === 1) return keyframes[0]
    
    // 计算当前在哪两个关键帧之间
    const segmentCount = keyframes.length - 1
    const segmentProgress = progress * segmentCount
    const segmentIndex = Math.floor(segmentProgress)
    const localProgress = segmentProgress - segmentIndex
    
    // 边界处理
    if (segmentIndex >= segmentCount) {
      return keyframes[keyframes.length - 1]
    }
    
    // 线性插值
    const start = keyframes[segmentIndex]
    const end = keyframes[segmentIndex + 1]
    
    return this.lerp(start, end, this.easeInOut(localProgress))
  }

  /**
   * 线性插值
   */
  lerp(start, end, t) {
    return start + (end - start) * t
  }

  /**
   * 缓动函数 - ease-in-out
   */
  easeInOut(t) {
    return t < 0.5 
      ? 2 * t * t 
      : -1 + (4 - 2 * t) * t
  }

  /**
   * 混合两个动画帧
   */
  blendFrames(frameA, frameB, progress) {
    const blended = {}
    
    // 获取所有属性
    const allKeys = new Set([...Object.keys(frameA), ...Object.keys(frameB)])
    
    for (const key of allKeys) {
      const valueA = frameA[key] || {}
      const valueB = frameB[key] || {}
      
      if (typeof valueA === 'object' && typeof valueB === 'object') {
        blended[key] = this.blendObjects(valueA, valueB, progress)
      } else {
        blended[key] = this.lerp(valueA || 0, valueB || 0, progress)
      }
    }
    
    return blended
  }

  /**
   * 混合两个对象
   */
  blendObjects(objA, objB, progress) {
    const blended = {}
    const allKeys = new Set([...Object.keys(objA), ...Object.keys(objB)])
    
    for (const key of allKeys) {
      const valueA = objA[key]
      const valueB = objB[key]
      
      if (typeof valueA === 'object' && typeof valueB === 'object') {
        blended[key] = this.blendObjects(valueA, valueB, progress)
      } else {
        blended[key] = this.lerp(valueA || 0, valueB || 0, progress)
      }
    }
    
    return blended
  }

  /**
   * 获取默认帧
   */
  getDefaultFrame() {
    return {
      body: { y: 0, rotation: 0, scale: 1 },
      tail: { rotation: 25 },
      ears: {
        left: { rotation: -15 },
        right: { rotation: 15 }
      },
      eyes: { scale: 1 },
      mouth: { curve: 0.5 },
      limbs: { offset: 0 }
    }
  }

  /**
   * 重置动画
   */
  reset(timestamp) {
    this.animationStartTime = timestamp
    this.transitionProgress = 1
    this.previousFrame = null
  }

  /**
   * 获取当前动画类型
   */
  getCurrentAnimationType() {
    return this.currentAnimation
  }

  /**
   * 添加自定义动画
   */
  addAnimation(name, config) {
    this.animations[name] = config
  }

  /**
   * 获取动画配置
   */
  getAnimationConfig(name) {
    return this.animations[name]
  }
}

export default AnimationManager
export { ANIMATIONS }
